﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media.Animation;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Web.Security;
using CCF20Model;
using System.Text;
using System.Collections.Generic;
using System.Reflection;
using System.Web.Profile;

namespace CCF20
{
    /// <summary>
    /// Interaction logic for Login.xaml
    /// </summary>
    public partial class LoginWindow : Window
    {
        private Storyboard closeStoryBoard;
        string[] PreLoadedAssembly = new string[]
            {
                "WiseLinkWPF.Windows.Controls.GridView.dll",
                "WiseLinkWPF.Windows.Controls.Navigation.dll",
                "WiseLinkWPF.Windows.Controls.dll",
                "WiseLinkWPF.Windows.Data.dll",
                "WiseLinkWPF.Windows.Controls.Input.dll",
                "WiseLinkWPF.Windows.Controls.Gauge.dll",
                "WiseLinkWPF.Windows.Controls.DataVisualization.dll"
            };
        public LoginWindow()
        {
            InitializeComponent();
            //closeStoryBoard = (Storyboard)FindResource("closeStoryBoard");


            string assemblyPath = Assembly.GetExecutingAssembly().Location.Replace("车务通无忧驾驶系统.exe", string.Empty);

            foreach (string assemblyName in PreLoadedAssembly)
            {
                System.Reflection.Assembly.LoadFrom(string.Format("{0}\\{1}",assemblyPath,assemblyName));
            }
          
            

            if (App.IsMobileBranch)
            {
                this.btnConfig.Visibility = System.Windows.Visibility.Hidden;
            }
            
        }
        private bool closeStoryBoardCompleted = false;
        
        private void Window_Closing(object sender, CancelEventArgs e) 
        {     
            //if (!closeStoryBoardCompleted)    
            //{         
            //    closeStoryBoard.Begin(this);   
            //    //e.Cancel = true;   
            //}
            this.Close();
        }
        private void closeStoryBoard_Completed(object sender, EventArgs e)
        {
            //closeStoryBoardCompleted = true;
            //this.Close();
        }
        private void RadButton_Click(object sender, RoutedEventArgs e)
        {
            string action = ((Button)sender).Tag.ToString();
            string userName = UserName.Text.Trim();
            string passWord = UserPassword.Password.Trim();
            bool isValidUser = false;
            
            if ( (action == "Login") && idsLoginInfo.Content.ToString().Contains("成功"))
            {
                if (userName.Equals("Admin",StringComparison.OrdinalIgnoreCase)
                    && passWord.Equals("Admin",StringComparison.OrdinalIgnoreCase))
                {
                    isValidUser = true;
                    
                }
                else if( Membership.ValidateUser(userName,passWord) )
                {
                    StringBuilder sb = new StringBuilder();
                    ModelFactory modelFactory = new ModelFactory();
                    PermissionModel permissionModel = (PermissionModel)modelFactory.CreateModel(ModelName.PermissionModel);
                    //IList<string> permissionList = new List<string>();
                    foreach (string role in Roles.GetRolesForUser(userName))
                    {
                        
                        Application.Current.Properties["AllowedPermission"] += permissionModel.GetPermissionForRole(role);
                        LoggerHelper.LogCCF20(string.Format("User={0} Permission={1}", userName, Application.Current.Properties["AllowedPermission"]));
                    }
                    isValidUser = true;

                    
                }

                if (isValidUser)
                {
                    Application.Current.Properties["CurrentUser"] = userName.ToLower();
                    ProfileBase profile = ProfileBase.Create(userName, true);
                    Application.Current.Properties["CurrentUserMobile"] = profile.GetPropertyValue("Mobile").ToString();

                    MainWindow mw = new MainWindow();
                    ZICMonitorModel.UpdateZICUrl(App.ZICUrl, App.IsJava);
                    this.Dispatcher.BeginInvoke(new Action(() => mw.Show()));
                    if (!App.IsMobileBranch)
                    {
                        this.Dispatcher.BeginInvoke(new Action(() => LaunchZICMonitor()));
                    }
                    Window_Closing(null, null);
                }
                else
                {
                    Utility.ShowMessageBox("用户名与密码不匹配!");
                }
            }else if (action == "Cancel")
            {
                //MainWindow.LoginSuccess = false;
                
                this.Close();
            }
            else if (action == "Configuration")
            {
                //MainWindow.LoginSuccess = false;

                Configuration config = new Configuration();
                config.ShowDialog();
            }
            else if (action == "IDSLogin")
            {
                //MainWindow.LoginSuccess = false;
                if (CCFZIC.CheckLogin(IDSName.Text.Trim(), IDSPassword.Password.Trim()))
                {
                    ProfileModel.SaveIDSUserPasswrod(IDSName.Text.Trim(), IDSPassword.Password.Trim());
                    idsLoginInfo.Content = "IDS登录成功";
                }
                else
                {
                    idsLoginInfo.Content = "IDS登录失败，请再试";
                }

            }
            else if (action == "ResetPassword")
            {
                if (this.panelChangePwd.Visibility == System.Windows.Visibility.Collapsed)
                {
                    this.panelChangePwd.Visibility = System.Windows.Visibility.Visible;
                }
                else
                {
                    this.panelChangePwd.Visibility = System.Windows.Visibility.Collapsed;
                }

            }
            else if (action == "ChangePassword")
            {
                
                if (Membership.ValidateUser(userName,passWord))
                {
                    MembershipUser mu = Membership.GetUser(userName);
                    if (mu.ChangePassword(passWord, this.NewPassword.Password.Trim()))
                    {

                        UserPassword.Password = null;
                        Utility.ShowMessageBox(string.Format("{0}密码更新成功", userName));
                        this.panelChangePwd.Visibility = System.Windows.Visibility.Collapsed;
                    }
                    else
                    {
                        Utility.ShowMessageBox(string.Format("{0}密码更新失败", userName));
                    }
                }

            }
        }
        private void RemoveOldLogFiles()
        {
            string path = System.Reflection.Assembly.GetExecutingAssembly().Location;

            string myDir = path.Remove(path.LastIndexOf("\\"));
            DirectoryInfo dirInfo = new DirectoryInfo(myDir);
            FileInfo[] files = dirInfo.GetFiles("*.log");
            foreach (FileInfo file in files)
            {
                if ((DateTime.Now - file.LastAccessTime) > new TimeSpan(7, 0, 0, 0))
                    file.Delete();
            }
        }
            
         
        private void LaunchZICMonitor()
        {
            Process[] runningProcs = Process.GetProcesses(".");
            foreach (Process p in runningProcs)
            {
                if (p.ProcessName.Contains("ZICMonitor"))
                {
                    p.Kill();
                }
            }

            string path = System.Reflection.Assembly.GetExecutingAssembly().Location;
            string myDir = path.Remove(path.LastIndexOf("\\"));
            DirectoryInfo dirInfo = new DirectoryInfo(myDir);
            FileInfo[] files = dirInfo.GetFiles("ZICMonitor.exe");
            if (files.GetLength(0) > 0)
            {
                Process.Start("ZICMonitor.exe");
            }
            else
            {
                Utility.ShowMessageBox(string.Format("无法找到ZICMonitor in {0}",myDir));
            }
        }
    }
}
